<?php
namespace Common\Model;

use Think\Model;
use Common\Model\OpenIdModel as OpenId;
use Common\Model\UserModel as User;
use Com\Weixin\WeixinApi;

class QrModel
{
    
    public function qr($userInfo ,$openid)
    {
        $userInfo['logo'] = $userInfo['logo'] ? $userInfo['logo'] : 'http://' . C('main_domain') . '/static/images/noHead.jpg';
        $userInfo['nickname'] = $userInfo['nickname'] ? $userInfo['nickname'] : "...";
    
        if ($userInfo['code3']) {
            $code3 = $userInfo['code3'];
        } else {
            $id_apply = new \Common\Model\IdApplyQrModel();
            $code3 = $id_apply->apply('code3');
        }
    
        //大于10W，用临时二维码
        $is_qr_limit = ($code3>100000) ? false : true;
    
        $path = $this->waterQr($userInfo['id'], $code3, $userInfo['nickname'], $userInfo['logo'] , false  ,$is_qr_limit );
        if ($path) {
            $path2 = APP_ROOT ."/Public". $path;
            if (file_exists($path2)) {
                $t = S('upload_limit');
    
                $wx_obj = new WeixinApi();
    
                if( $t==false ){
                    @chmod($path2, 0777);
    
    
                    $access_token = $wx_obj->getToken( );
    
                    $cmd = 'curl -F media=@' . $path2 . ' "http://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image"';
                    $rs1 = trim(exec($cmd));
                    $rs = json_decode($rs1, true);
                    if ($rs['media_id']) {
                        $media_id = $rs['media_id'];
                        $u = new User();
                        $where['id'] = $userInfo['id'];
                        $update = array();
                        $update['code3'] = $code3;
                        $u->where($where)->save($update);
    
                        $open_obj = new OpenId();
                        $where = array();
                        $where['uid'] = $userInfo['id'];
                        $where['wxhao'] = C('WX_HAO');
                        $update = array();
                        $update['media_id'] = $media_id;
                        $update['media_time'] = time();
                        $update['media_path'] = $path;
                        $update['media_limit'] = $is_qr_limit ? 1 : 0;
                        $open_obj->where($where)->save($update);
    
                        $wx_obj->sendPicture($openid, $media_id);
    
                    } else {
                        $expire = (strtotime( date("Y-m-d 00:00:00") )+3600*24)- time();
                        S('upload_limit' , 1 , $expire );
                        my_log('上传图片失败：'.$rs1);
                        echo ($rs1);
                    }
                }else{
                    $open_obj = new OpenId();
                    $where = array();
                    $where['uid'] = $userInfo['id'];
                    $where['wxhao'] = C('WX_HAO');
                    $update = array();
                    $update['media_id'] = '';
                    $update['media_time'] = time();
                    $update['media_path'] = $path;
                    $open_obj->where($where)->save($update);
    
                    $domain = C('main_domain');
    
                    $content = <<<EOT
<a href='http://{$domain}{$path}'>点击此次查看你的二维码</a>
  
长按图片，保存到手机。记得发给你的小伙伴啊！
EOT;
    
                    $wx_obj->sendPicture($openid, $content);
                }
            } else {
                my_log('找不到上传图片：'.$path);
                echo ($path);
            }
        } else {
            my_log('打水印失败：'.$path);
        }
    }
    
    /**
     * 对二维码加工
     * @param unknown $uid        用户UID
     * @param unknown $code       标示
     * @param unknown $nickname   昵称
     * @param unknown $logo_url   Logo图片地址
     * @param string $code_is_str 二维码标示是否字符串
     * @param string $is_qr_limit 是否永久二维码
     */
    public function waterQr($uid, $code, $nickname, $logo_url, $code_is_str = false, $is_qr_limit = true )
    {
        $path = C('QR_PATH');
    
        $name = md5($uid);
        $dir1 = substr($name, 0, 2);
        $dir2 = substr($name, 2, 2);
    
        $path = $path . $dir1 . '/' . $dir2 . '/';
    
        $filename = $uid .'_'.time(). '_qr2.png';
    
        // 腾讯的二维码
        $p = $this->getQr($uid, $code, $code_is_str , $is_qr_limit );
        if (! $p) {
            my_log('获取腾讯的二维码失败, uid:'.$uid);
            return false;
        }
        $p = APP_ROOT ."/Public" .$p;
    
    
        $image_p = new \Think\Image(1, $p);
        
        $configObj = new ConfigModel();
        
        //二维码缩略图大小
        $qr_size = $configObj->getConfig('QR_THUMB_SIZE');
        list($qr_w , $qr_h) = explode(',', $qr_size);
        if( !$qr_w || !$qr_h ){
            $qr_w = $qr_h = 235;
        }
        $image_p->thumb($qr_w, $qr_h);
        $image_p->save($p);
    
        //头像缩略图大小
        $logo_size = $configObj->getConfig('QR_LOGO_THUMB_SIZE');
        list($logo_w , $logo_h) = explode(',', $logo_size);
        if( $logo_w && $logo_h ){
            //下载Logo并且缩略图
            $logo_path = APP_ROOT  . '/Public'. $path . $uid . "_logo.png";
            if (! file_exists($logo_path) || filesize($logo_path) <= 0 ) {
                $http = new \Org\Net\Http();
                $http->curlDownload($logo_url, $logo_path);
                if( !file_exists( $logo_path ) || filesize($logo_path) <= 0 ){
                    my_log('下载Logo并且缩略图失败, uid:'.$uid);
                	return false;
                }
            }
            $image2 = new \Think\Image(1, $logo_path);
            
            
            $image2->thumb($logo_w, $logo_h);
            $image2->save($logo_path);
        }
    
        $new_path = APP_ROOT . '/Public'. $path;
        if (! is_dir($new_path)) {
            mkdirs($new_path,0755);
        }
    
        $path_name = $new_path . $filename;
    
        //         if (file_exists($path_name)) {
        //             return $path . $filename;
        //         }
    
        $path2 = APP_ROOT . '/Public/static/images/tpl_' . C('WX_HAO') . '.png';
        if( !file_exists($path2) ){
            my_log('底图模板文件不存在'.$path2);
            return false;
        }
    
        $image = new \Think\Image(1, $path2);
    
        //头像缩略图位置
        $logo_pos = $configObj->getConfig('QR_LOGO_POSITION');
        list($logo_left , $logo_top) = explode(',', $logo_pos);
        //logo图像存在
        if( $image2 && file_exists($logo_path) && $logo_left && $logo_top  ){
            
            $pos = array(
                $logo_left,
                $logo_top
            );
            //logo
            $image->water($logo_path, $pos, 100);
        }
    
        //二维码位置
        $qr_pos = $configObj->getConfig('QR_POSITION');
        list($qr_left , $qr_top) = explode(',', $qr_pos);
        $qr_left = $qr_left ? $qr_left :0;
        $qr_top = $qr_top ? $qr_top : 0;
        $pos = array(
            $qr_left,
            $qr_top
        );
        //二维码
        $image->water($p, $pos, 100);
    
    
        //昵称位置
        $nickname_pos = $configObj->getConfig('QR_NICKNAME_POSITION');
        list($nickname_left , $nickname_top) = explode(',', $nickname_pos);    
        if( $nickname_left && $nickname_top ){
            $pos = array(
                $nickname_left,
                $nickname_top
            );
            //昵称
            $image->text($nickname, APP_ROOT . '/ThinkPHP/Library/Think/Image/Font/heiti.ttf', 30, '#00000000', 1, $pos);
        }
        
        //有效期位置
        $expire_pos = $configObj->getConfig('QR_EXPIRE_POSITION');
        list($expire_left , $expire_top) = explode(',', $expire_pos);
        
        $pos = array(
            $expire_left,
            $expire_top
        );
        if( $expire_left && $expire_top ){
            //有效期
            $expire ="长期";
            if( $is_qr_limit == false ){
                $expire = date('Y-m-d H:i:s' ,strtotime('+30 day') );
            }
            $pos = array(
                $expire_left,
                $expire_top
            );
            $image->text($expire, APP_ROOT . '/ThinkPHP/Library/Think/Image/Font/heiti.ttf', 16, '#00000000', 1, $pos);
        }
        
        $image->save($path_name);
    
        return $path . $filename;
    }
    
    
    /**
     * 获取腾讯二维码图片并且保存
     * @param unknown $uid
     * @param unknown $code
     * @param string $code_is_str
     * @return string|boolean
     */
    public function getQr($uid, $code, $code_is_str = false , $is_qr_limit = true )
    {
        $path = C('QR_PATH');
    
        $name = md5($uid);
        $dir1 = substr($name, 0, 2);
        $dir2 = substr($name, 2, 2);
    
        $path = $path . $dir1 . '/' . $dir2 . '/';
    
        $filename = $uid . '_qr.png';
    
        $new_path = APP_ROOT ."/Public". $path;
        if (! is_dir($new_path)) {
            mkdirs($new_path,0755);
        }
    
        $path_name = $new_path . $filename;
    
        if (file_exists($path_name) && filesize( $path_name )>0 && $is_qr_limit ) {
            return $path . $filename;
        }
    
        $wx_obj = new WeixinApi();
        $access_token = $wx_obj->getToken( );
    
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token;
    
        $data = array();
    
        //永久二维码
        if( $is_qr_limit ){
            if ( $code_is_str ) {
                $data['action_name'] = 'QR_LIMIT_STR_SCENE';
                $data['action_info']['scene']['scene_str'] = $code;
            } else {
                $data['action_name'] = 'QR_LIMIT_SCENE';
                $data['action_info']['scene']['scene_id'] = $code;
            }
        }
        //临时二维码
        else{
            $data['action_name'] = 'QR_SCENE';
            $data['expire_seconds'] = 2592000;
            $data['action_info']['scene']['scene_id'] = $code;
        }
    
        $data = JSON($data);
        $rs = https_request($url, $data);
        $rs1 = json_decode($rs, true);
        if ($rs1 && $rs1['ticket']) {
            $ticket = $rs1['ticket'];
            $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);
    
            // $http = new \Org\Net\Http();
            // $http->curlDownload( $path_name, $path_name);
            
            // start 采用file_put_contents方式生成二维码 last_update time 2016-04-15 by 1741159138@qq.com
            file_put_contents( $path_name, file_get_contents($url));
            // end
            if( !file_exists( $path_name ) ){
                my_log( "curlDownload下载图片失败 ,uid: ".$uid );
            }

            if( file_exists( $path_name ) && filesize($path_name)>0 ){
                return $path . $filename;
            }
            
        }else{
            my_log( "get qr fail : ".implode(',', $rs1) );
        }
    
        return false;
    }
}